


$(document).ready(function () {
	datatablePlugins();
	iniClientDatatable();
	buttonEvents();
	//_datatableEvents();
	tmp();
});


/**
 * for test purposes only
 */
function tmp() {
	
		
}

/**
 * this function is added to the prototype of datatable plugin so we can reload 
 * data from server and use the local search feacture (avoiding this way the use of the server by the search field)
 */
function datatablePlugins() {
	
	// fnReloadAjax
	$.fn.dataTableExt.oApi.fnReloadAjax = function ( oSettings, sNewSource, fnCallback, bStandingRedraw )
	{
	    if ( typeof sNewSource != 'undefined' && sNewSource != null )
	    {
	        oSettings.sAjaxSource = sNewSource;
	    }
	    this.oApi._fnProcessingDisplay( oSettings, true );
	    var that = this;
	    var iStart = oSettings._iDisplayStart;
	    var aData = [];
	 
	    this.oApi._fnServerParams( oSettings, aData );
	     
	    oSettings.fnServerData( oSettings.sAjaxSource, aData, function(json) {
	        /* Clear the old information from the table */
	        that.oApi._fnClearTable( oSettings );
	         
	        /* Got the data - add it to the table */
	        var aData =  (oSettings.sAjaxDataProp !== "") ?
	            that.oApi._fnGetObjectDataFn( oSettings.sAjaxDataProp )( json ) : json;
	         
	        for ( var i=0 ; i<aData.length ; i++ )
	        {
	            that.oApi._fnAddData( oSettings, aData[i] );
	        }
	         
	        oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
	        that.fnDraw();
	         
	        if ( typeof bStandingRedraw != 'undefined' && bStandingRedraw === true )
	        {
	            oSettings._iDisplayStart = iStart;
	            that.fnDraw( false );
	        }
	         
	        that.oApi._fnProcessingDisplay( oSettings, false );
	         
	        /* Callback user function - for event handlers etc */
	        if ( typeof fnCallback == 'function' && fnCallback != null )
	        {
	            fnCallback( oSettings );
	        }
	    }, oSettings );
	};
}


function iniClientDatatable() {
	
	// feed the datatable from this link
	var serverRequest = window.ajaxUrl + '/readClientAction';
	
	var clientTable = $('#clientTable');
	
	var clientForm = $('#clientForm');
	
	var createButton = $('#createButton');
	
	// clientId = 0 means no client data is in the form
	clientForm.attr('data-id',0);

	// datatable options 
	var tableProperties = {
		'sDom':				"<'row'<'span8'l><'span4'f>r>t<'row'<'span8'i><'span4'p>>", // bootstrap integration
		'sAjaxSource': 		serverRequest,	
		'sServerMethod':	'POST',
		'sAjaxDataProp': 	'data',
		'fnServerParams': 	function (aoData) {
				aoData.push( {'var1':'value1','var2':'value2'});
		},
		"aoColumns": [
			{"mDataProp":"name"},
			{"mDataProp":"address"},
			{"mDataProp":"email"},
			{"mDataProp":"phone"},
			{"mDataProp":"birthday"}
		],
		//'sPaginationType': "bootstrap", // ... need a plugin to work
		'bJQueryUI':		false,	// enable jqueryUI Themes
		'bPaginate':		true,
		'bSort':			true,
		'bInfo':			true,
		'bAutoWidth':		true,
		'bProcessing': 		true,
		'bServerSide': 		false,	// use server side processing
		'oLanguage': {
			'sInfo':		'registos _START_ até ao _END_ de _TOTAL_',
			'sZeroRecords': 'Não existem registos',
			'sSearch':		'Procurar',
			'sLengthMenu':	'Mostrar <select>' +
				'<option value="5">5</option>'+
				'<option value="10">10</option>'+
		        '<option value="20">20</option>'+
		        '<option value="30">30</option>'+
		        '<option value="40">40</option>'+
		        '<option value="50">50</option>'+
		        '<option value="-1">Todos</option>'+
		        '</select> registos'
		}	
	};

	// set datatable options
	clientTable.dataTable(tableProperties);
	
	// datatable CLICK EVENTS
	clientTable.find('tbody tr').live('click',function() {

		// get data from the selected row
		clientData = clientTable.fnGetData(this); 
		
		// break here if there is no client in the table
		if ( !clientData )
			return;
		
		if ( $(this).hasClass('row_selected') ) { // ... the row is already selected
			
            $(this).removeClass('row_selected'); 
            
            // reset clientForm
            clearClientForm();
		} 
		else { // ... no row selected
			
	        // avoid multi selected row ... 
           	clientTable.$('tr.row_selected').removeClass('row_selected');
           	
           	// highlight selected row
            $(this).addClass('row_selected');
            
            // change button label
           	createButton.html('Atualizar'); 
           	
            // set the client id
			clientForm.attr('data-id',clientData.id);
			
			// fill form with all client info
			clientForm.find('#clientName').val(clientData.name).next().html('').parents('.control-group').attr('class','control-group success');
			clientForm.find('#clientAddress').val(clientData.address).next().html('').parents('.control-group').attr('class','control-group success');
			clientForm.find('#clientEmail').val(clientData.email).next().html('').parents('.control-group').attr('class','control-group success');
			clientForm.find('#clientPhone').val(clientData.phone).next().html('').parents('.control-group').attr('class','control-group success');
			clientForm.find('#clientHeight').val(clientData.height).next().html('').parents('.control-group').attr('class','control-group success');
			clientForm.find('#clientBirthday').val(clientData.birthday).next().html('').parents('.control-group').attr('class','control-group success');
			clientForm.find('#clientWeight').val(clientData.weight).next().html('').parents('.control-group').attr('class','control-group success');
			clientForm.find('#clientSex').val(clientData.sex);
			clientForm.find('#clientNationality').val(clientData.nationality).next().html('').parents('.control-group').attr('class','control-group success');
			clientForm.find('#clientInfo').val(clientData.info);
		}
	});
}




/**
 * treat here all button events
 */
function buttonEvents() {
	
	var clientTable = $('#clientTable').dataTable();
	
	var createButton = $('#createButton');
	
	createButton.click(function(event) {
		
		// prevent form submission. Ajax will be used instead
		event.preventDefault();
		
		// validate fields 
		
	});
	
	return;
	
	//rightButtonOpt.__proto__ = mainButtonOpt; // extend

	leftButtonOpt = new Object();
	//leftButtonOpt.__proto__ = mainButtonOpt;
	leftButtonOpt.label = 'limpar';
	leftButtonOpt.text = true;
	leftButtonOpt.icons = {
		primary:	'ui-icon-cancel',
		secondary:	'ui-icon-triangle-1-e'
	};
	
	

	// create jqueryUI button
	var rightButton 	= $("#rightButton");
	var leftButton 		= $("#leftButton");
	
	rightButton.button(rightButtonOpt);
	leftButton.button(leftButtonOpt);
	
	var deleteButton 	= $('#deleteButton');
	
	deleteButton.button({
		label: 		'delete',
		text: 		true,
		disabled: 	true,
		icons: {
			primary:	'ui-icon-trash',
			secondary:	'ui-icon-triangle-1-n'
		}
	});

	var clientBrithday 	= $('#clientBirthday');
	var clientForm 		= $('#clientForm');
	
	// CREATE/UPDATE button
	rightButton.click(function() {
		
		//clientBrithday.datepicker('disable');
		
		//check if all form fields are ok
		var validate = clientForm.validationEngine('validate');

		clientBrithday.datepicker('hide');

		// break if the data is unvalid
		if(!validate)
			return;
		
		
		// if it is a new client ... check if the email is already registered
		/*
		if(clientForm.attr('data-id') == 0) {
			$.getJSON(window.hotelInfo + "/tmp", {
					email: clientInfo.email
				},
				function(data) {
					if (data.exists) { // client exists
						//console.log(data.msg);
						$('#clientExistsAlert').dialog({
							width:		480,
							height:		200,
							show: 		'fade',
							hide: 		'fade',
							buttons: {
								"Ok": function() {
									$(this).dialog("close");
								}
							}
						});
						return;
					}
					else {
						console.log('criar este cliente');
						loadExtras(schoolId, offerId);
						reservationOptionDialog(clientId, offerId, schoolId,clientInfo);
					}
					//console.log('data from tmp: ', data);
				}
			);
		}
		*/
		
		
		// set the languages spoken by the client in an hidden field
		var arrWithLanguages = [];
		var languages = $('#clientLanguages li input:checked');
		languages.each(function(){
			arrWithLanguages.push($(this).val());
		});
		clientForm.find('#hiddenLanguages').val(arrWithLanguages.join('&'));

		// get all attr 'name' from the client
		var clientInfo = {};
		jQuery.each($('#clientForm').serializeArray(), function(i, field) {
			clientInfo[field.name] = field.value;
		});

		// the client identification is retrieved from this attribute
		clientInfo['clientId'] = clientForm.attr('data-id');
		
		// create or update?
		if (clientInfo['clientId'] == 0) { 
			
			sendClientData2Server( clientInfo , '/createClientAction' );
			
            // reset form
			//clientForm.validationEngine('hide');
            //clientForm[0].reset();

            // set id to 0 to indicate there is no data client in the form 
			clientForm.attr('data-id',0);
		}
		else { 
			
			sendClientData2Server( clientInfo , '/updateClientAction' );
			
			rightButton.button('option','label','criar'); 
			
			deleteButton.button('option','disabled',true);
		}
	});
}











/**
 * handle here the events of datatable
 */
function _datatableEvents() {

	// reference to datatable
	var clientTable = $('#clientTable').dataTable();
	
	// clientData retrieved from the datatable
	var clientData = null;

	// form with client data
	var clientForm = $('#clientForm'); 

	// this attr indicates no client is loaded in the form
	clientForm.attr('data-id',0);

	// button to create/update client
	var rightButton 	= $('#rightButton'); 
	
	var deleteButton 	= $('#deleteButton'); 

	// datatable click event
	$('#clientTable tbody tr').live('click', function() {
		
		// checkboxes with the client spoken languages 
		var langInputs = $('#clientLanguages li input');
			
		if ( $(this).hasClass('row_selected') ) { // ... the row is already selected

			// remove the selection
            $(this).removeClass('row_selected'); 

            // reset form
            clientForm[0].reset();

            // set id to 0 to indicate there is no data client in the form 
			clientForm.attr('data-id',0);
			
			// clear previous selections
			langInputs.removeAttr('checked');

			// change the label of the button
           	rightButton.button('option','label','criar'); 
           	
           	// disable delete button
           	deleteButton.button('option','disabled',true);
        }
        else { // no row selected ...

        	// enable delete button
           	deleteButton.button('option','disabled',false);
           	
	        // avoid multi selected row ... 
           	clientTable.$('tr.row_selected').removeClass('row_selected');

           	// highlight selected row
            $(this).addClass('row_selected');

            // change button label
           	rightButton.button('option','label','Actualizar'); 
           	
            //var nTds = $('td', this);
            
            // get all client information 
			clientData = clientTable.fnGetData(this); 

            // set the client id
			clientForm.attr('data-id',clientData.id);
			
			// fill form with all client info
			clientForm.find('#clientName').val(clientData.name);
			clientForm.find('#clientAddress').val(clientData.address);
			clientForm.find('#clientEmail').val(clientData.email);
			clientForm.find('#clientPhone').val(clientData.phone);
			clientForm.find('#clientHeight').val(clientData.height);
			clientForm.find('#clientBirthday').val(clientData.birthday);
			clientForm.find('#clientWeight').val(clientData.weight);
			clientForm.find('#clientSex').val(clientData.sex);
			clientForm.find('#clientNationality').val(clientData.nationality);
			clientForm.find('#clientInfo').val(clientData.info);
			
			// get the languages spoken by the selected client
			$.ajax({
				url: 		window.ajaxUrl + '/clientLanguages',
				type:		'POST',
				dataType:	'json',
				data: {
					clientId:	clientData.id
				},
				success: 	function(data) {
					
					langInputs.removeAttr('checked');
					
					if (data.length!=0) {
						
						// check retrieved languages
						$.each(data, function(key,value){
							var sel = 'input[value=' + value.domain + ']';
							langInputs.parent().find(sel).attr('checked','checked');
						});
					}
				},
				error:		function(xhr, status){},
				complete:	function(xhr,status){}
			});
        }
	});
}





/**
 * Remove all data from clientForm fields
 * Remove any message
 * set hidden attr 'clientId' to '0' and
 * update the label of the button to 'createClient'
 */
function clearClientForm() {
	
	var clientForm = $('#clientForm');
	
	var createButton = $('#createButton');
	
	// clear all 'input' fields inside clientForm
	clientForm.children().each(function(i,e) {
		
		var input = $(this).find('.controls input:text');
		
		if (input.length > 0) {
			
			$(this).attr('class','control-group')
				.find('input')
				.val('') .end()
				.find('.help-inline')
				.html('');
		}
	});
	
	// clear the textarea
	//$('#clientInfo .controls textarea').val('');
	
	// reset the clientId
	clientForm.attr('data-id',0);
	
	// remove all 'error' 'success' messages
	$('#createClientAlert').removeClass('alert alert-error alert-success').html('');
	
	// update the button label
    createButton.html('Criar Cliente');
}





/**
 * Function to update, delete or create a client
 * @param values - values to send to the server
 * @param methodName - the name of the function to process the data
 */
function sendClientData2Server(values, methodName) {
	
	$.ajax({
		url:		window.ajaxUrl + methodName, 
		type:		'POST',		// type of request to make
		async:		true,		// asynchronous/synchronous request
		dataType:	"json",		// type of data returned from server
		
		data: values,
		
		// request was successful ... 'data' is received from server
		success: 	function(data, textStatus, jqXHR) {
			
			// reload data from server
			$('#clientTable').dataTable().fnReloadAjax();
			
			var alertDialog = $('#dialog');
			alertDialog.attr('title','dialog').html(data.msg);
			alertDialog.dialog({
				width:		550,
				height:		250,
				show: 		'fade',
				hide: 		'fade',
				autoOpen:	true,
				modal:		true,
				buttons: {
					"Ok": 		
					function() {
						$('#clientForm')[0].reset();
						$('#clientForm').attr('data-id',0);
						$(this).dialog("close");
					}
				}
			});
		},

		// something went wrong ...
		error:		function(jqXHR, textStatus, errorThrown) {	
		},
		
		// code to run regardless of success or failure
		complete: function(xhr, status) {
		}
	});
}


